package com.cqhilink.iot.jobstandardmanagement.services.innerservice.impl.workcellinstance;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cqhilink.api.common.utils.UniqueUtil;
import com.cqhilink.api.common.utils.annotation.AnnotationDealUtil;
import com.cqhilink.api.common.utils.date.DateStyle;
import com.cqhilink.api.common.utils.date.DateUtil;
import com.cqhilink.iot.jobstandardmanagement.facade.service.workCellDataSet.JsmIWorkCellDataSetService;
import com.cqhilink.iot.jobstandardmanagement.facade.utils.OrganizationLevel;
import com.cqhilink.iot.jobstandardmanagement.facade.utils.TreeIconSkin;
import com.cqhilink.iot.jobstandardmanagement.facade.utils.WorkInstanceLevel;
import com.cqhilink.iot.jobstandardmanagement.dao.mapper.EntityMapper;
import com.cqhilink.iot.jobstandardmanagement.dao.mapper.SingleWorkStepMapper;
import com.cqhilink.iot.jobstandardmanagement.dao.mapper.WorkCellInfoMapper;
import com.cqhilink.iot.jobstandardmanagement.dao.mapper.WorkCellInstanceMapper;
import com.cqhilink.iot.jobstandardmanagement.facade.model.*;
import com.cqhilink.iot.jobstandardmanagement.facade.service.entitytype.JsmEntityTypeService;
import com.cqhilink.iot.jobstandardmanagement.facade.service.operateunit.JsmOperateUnitService;
import com.cqhilink.iot.jobstandardmanagement.facade.service.operatingunitform.JsmOperatingUnitFormService;
import com.cqhilink.iot.jobstandardmanagement.facade.service.organization.JsmOrganizationService;
import com.cqhilink.iot.jobstandardmanagement.facade.service.servicenode.JsmServiceNodeService;
import com.cqhilink.iot.jobstandardmanagement.facade.service.singlework.JsmSingleWorkService;
import com.cqhilink.iot.jobstandardmanagement.facade.service.station.JsmStationService;
import com.cqhilink.iot.jobstandardmanagement.facade.service.version.JsmVersionService;
import com.cqhilink.iot.jobstandardmanagement.facade.service.well.JsmWellService;
import com.cqhilink.iot.jobstandardmanagement.facade.service.workcellinfo.JsmIRelatedDocService;
import com.cqhilink.iot.jobstandardmanagement.facade.service.workcellinstance.JsmWorkCellInstanceService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * Created by zmling on 2016/12/8.
 * modify by huangxueqian 2017/02/22
 * 一站一案 服务实现
 */

public class JsmWorkCellInstanceServiceImpl implements JsmWorkCellInstanceService {
    @Autowired
    private WorkCellInstanceMapper workCellInstanceMapper;
    @Autowired
    private JsmOperatingUnitFormService jsmOperatingUnitFormService;
    @Autowired
    private JsmVersionService versionService;
    @Autowired
    private WorkCellInfoMapper workCellInfoMapper;
    @Autowired
    private JsmSingleWorkService singleWorkService;
    @Autowired
    private SingleWorkStepMapper stepMapper;
    @Autowired
    private JsmStationService stationService ;
    @Autowired
    private JsmEntityTypeService entityTypeService ;
    @Autowired
    private JsmOrganizationService organizationService ;
    @Autowired
    private EntityMapper entityMapper;
    @Autowired
    private JsmOperateUnitService operateUnitService;
    @Autowired
    private JsmWellService wellService;
    @Autowired
    private JsmServiceNodeService serviceNodeService ;
    @Autowired
    private JsmIRelatedDocService relatedDocService ;
    @Autowired
    private JsmIWorkCellDataSetService dataSetService ;
    /**
     * 新增
     * @param workCellInstance
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int addWorkCellInstance(WorkCellInstance workCellInstance,EmployeeVo employee) throws Exception {
        int resInt = 0;
        workCellInstance.setWorkInstanceId(UniqueUtil.uuid());
        workCellInstance.setCreateopid(employee.getEmployeeId());
        workCellInstance.setCreatetime(new Date());
        workCellInstance.setModifyopid(employee.getEmployeeId());
        workCellInstance.setModifytime(new Date());
        workCellInstance.setStatus((short) 0);
        workCellInstance.setType((short) 0);
        if(StringUtils.isNotEmpty(workCellInstance.getEntityId())){
            Organization organization =  organizationService.selectOrgByOrgId(workCellInstance.getEntityId());
            workCellInstance.setIconSkin(organizationService.offsetIconSkin(organization));
        }
        if(TreeIconSkin.ICON_BUIDING.getDesc().equals(workCellInstance.getIconSkin())){
            //分公司
            workCellInstance.setWorkType(WorkInstanceLevel.ORG_LEVEL_BRANCH.getCode());
        }else  if(TreeIconSkin.ICON_FLAG.getDesc().equals(workCellInstance.getIconSkin())){
            //气矿
            workCellInstance.setWorkType(WorkInstanceLevel.ORG_LEVEL_GAS_FIELD.getCode());
        }else  if(TreeIconSkin.ICON_OA.getDesc().equals(workCellInstance.getIconSkin())){
            //作业区
            workCellInstance.setWorkType(WorkInstanceLevel.ORG_LEVEL_WORK_SPACE.getCode());
        }else  if(TreeIconSkin.ICON_STATION.getDesc().equals(workCellInstance.getIconSkin())){
            //场站
            workCellInstance.setWorkType(WorkInstanceLevel.ORG_LEVEL_STATION.getCode());
        }else  if(TreeIconSkin.IONC_WELL.getDesc().equals(workCellInstance.getIconSkin())){
            //井站
            workCellInstance.setWorkType(WorkInstanceLevel.ORG_LEVEL_WELL.getCode());
        }else  if(TreeIconSkin.IONC_PIPELINE.getDesc().equals(workCellInstance.getIconSkin())){
            //管线
            workCellInstance.setWorkType(WorkInstanceLevel.ORG_LEVEL_PIPELINE.getCode());
        }else if(TreeIconSkin.ICON_DEVICE.getDesc().equals(workCellInstance.getIconSkin())){
            //设备
            workCellInstance.setWorkType(WorkInstanceLevel.ORG_LEVEL_DEVICE.getCode());
        }
        resInt = workCellInstanceMapper.insertSelective(workCellInstance);
        if (resInt > 0 && !org.springframework.util.StringUtils.isEmpty(workCellInstance.getCellId())) {
            /**
             * 新增一站一案成功之后；新增出操作步骤等操作 ， 克隆步骤 和 步骤表单 和 克隆文档
             */
            WorkCellInfo workCellInfo = workCellInfoMapper.selectByPrimaryKey(workCellInstance.getCellId());
            // 克隆操作步骤
            operateUnitService.cloneStep(workCellInfo, workCellInstance,employee);
                // 复制文档
                try {
                    relatedDocService.cloneDoc(workCellInfo, workCellInstance,employee);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // 复制表单
            // 复制操作表单
            jsmOperatingUnitFormService.cloneOperateForm(workCellInfo, workCellInstance,employee);


        }

        return resInt;
    }


    /**
     * @param workCellInstance
     * @param employee
     * 批量导入操作卡， 该方法只适用于批量导入操作卡的的步骤
     */
    public WorkCellInstance saveWorkCellInstance(WorkCellInstance workCellInstance,EmployeeVo employee) throws Exception {
        workCellInstance.setWorkInstanceId(UniqueUtil.uuid());
        workCellInstance.setCreateopid(employee.getEmployeeId());
        workCellInstance.setCreatetime(new Date());
        workCellInstance.setModifyopid(employee.getEmployeeId());
        workCellInstance.setModifytime(new Date());
        workCellInstance.setStatus((short) 0);
        workCellInstance.setType((short) 0);
        if(TreeIconSkin.ICON_BUIDING.getDesc().equals(workCellInstance.getIconSkin())){
            //分公司
            workCellInstance.setWorkType(WorkInstanceLevel.ORG_LEVEL_BRANCH.getCode());
        }else  if(TreeIconSkin.ICON_FLAG.getDesc().equals(workCellInstance.getIconSkin())){
            //气矿
            workCellInstance.setWorkType(WorkInstanceLevel.ORG_LEVEL_GAS_FIELD.getCode());
        }else  if(TreeIconSkin.ICON_OA.getDesc().equals(workCellInstance.getIconSkin())){
            //作业区
            workCellInstance.setWorkType(WorkInstanceLevel.ORG_LEVEL_WORK_SPACE.getCode());
        }else  if(TreeIconSkin.ICON_STATION.getDesc().equals(workCellInstance.getIconSkin())){
            //场站
            workCellInstance.setWorkType(WorkInstanceLevel.ORG_LEVEL_STATION.getCode());
        }else  if(TreeIconSkin.IONC_WELL.getDesc().equals(workCellInstance.getIconSkin())){
            //井站
            workCellInstance.setWorkType(WorkInstanceLevel.ORG_LEVEL_WELL.getCode());
        }else  if(TreeIconSkin.IONC_PIPELINE.getDesc().equals(workCellInstance.getIconSkin())){
            //管线
            workCellInstance.setWorkType(WorkInstanceLevel.ORG_LEVEL_PIPELINE.getCode());
        }else if(TreeIconSkin.ICON_DEVICE.getDesc().equals(workCellInstance.getIconSkin())){
            //设备
            workCellInstance.setWorkType(WorkInstanceLevel.ORG_LEVEL_DEVICE.getCode());
        }
        workCellInstanceMapper.insertSelective(workCellInstance);

        return workCellInstance;
    }



    /**
     * 新增一站一案配置后， 初始化数据{包含操作步骤；操作表单；操作数据项}
     */
    private void workCellInstanceAdd(WorkCellInstance workCellInstance,EmployeeVo employee) throws Exception {
        /**
         *  判断当前一站一案   ：
         *  版本步骤表是否存在 ;
         *  不存在则新增版本   ;
         */
        Version version = new Version();
        version.setRelatedId(workCellInstance.getWorkInstanceId());
        version.setVersionNumber(workCellInstance.getStepVersion());
        Version versionHas = versionService.queryVersion(version);
        if (versionHas == null) {
            version.setVersionName("初始版本");
            versionService.addVersion(version,employee);
        }
        /**
         * 查询操作单元当前步骤；初始化到一站一站操作步骤
         */
        this.cloneCellToInstance(workCellInstance,employee);

    }


    /**
     * 将操作单元的操作步骤；复制到一站一案
     *
     * @param workCellInstance
     */
    private void cloneCellToInstance(WorkCellInstance workCellInstance,Employee employee) {

        SingleWorkStep step = new SingleWorkStep();
        step.setCellId(workCellInstance.getCellId());
        step.setVersion(workCellInstance.getStepVersion());
        //step.setWorkContentId(workCellInstance.getWorkInstanceId());
        if (workCellInstance != null) {
            /**
             * 查询 操作步骤
             */
            List<SingleWorkStep> singleWorkStepList = stepMapper.selectByStepSelect(step);
            if (singleWorkStepList != null) {
                for (SingleWorkStep workStep : singleWorkStepList) {
                    workStep.setStepId(UniqueUtil.uuid());
                    workStep.setWorkContentId(workCellInstance.getWorkInstanceId());
                    workStep.setCreateTime(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM));
                    workStep.setModifyTime(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM));
                    workStep.setCreatorId(employee.getEmployeeId());
                    workStep.setModifierId(employee.getEmployeeId());
                    stepMapper.insertSelective(workStep);
                }
            }
        }

    }


    /**
     *  一站一案获取列表分页
     * @param  workCellInstance
     */
    @Override
    public JSONObject table(WorkCellInstanceVo workCellInstance) throws Exception {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("total", workCellInstanceMapper.queryCount(workCellInstance));
            jsonObject.put("rows", JSON.toJSON(workCellInstanceMapper.queryList(workCellInstance)));
        return jsonObject;
    }

    /**
     * 根据主键查询
     *
     * @param workInstanceId
     * @return
     * @throws Exception
     */
    @Override
    public WorkCellInstanceVo loadWorkCellInstanceView(String workInstanceId) throws Exception {
        return workCellInstanceMapper.selectByPrimaryKey(workInstanceId);
    }

    /**
     * 删除一站一案内容
     */
    @Override
    public int deleteWorkCellInstance(Map workInstances) throws Exception {
        return workCellInstanceMapper.updateWorkCellInstanceById(workInstances);
    }

    /**
     * 修改
     *
     * @param workCellInstance
     * @return
     * @throws Exception
     */
    @Override
    public int upateWorkCellInstance(WorkCellInstance workCellInstance,Employee employee) throws Exception {
        workCellInstance.setModifyopid(employee.getEmployeeId());
        workCellInstance.setModifytime(new Date());
        return workCellInstanceMapper.updateByPrimaryKeySelective(workCellInstance);
    }

    /**
     * 为其他系统提供工作内容接口
     *
     * @param workCellInstance
     * @return
     * @throws Exception
     */
    @Override
    public List<WorkCellInstance> outFindWorkCellInstanceList(WorkCellInstance workCellInstance) throws Exception {
        return workCellInstanceMapper.outFindWorkCellInstanceList(workCellInstance);
    }

    /**
     * @param workCellInstanceVo
     * @return JSONObject
     * @Author 卢曼成
     * @Description
     * @Date 2017/2/24 13:58
     */
    @Override
    public JSONObject queryInstanceInfoUnionList(WorkCellInstanceVo workCellInstanceVo) throws Exception {
        JSONObject jsonObject = new JSONObject();
        workCellInstanceVo.setLimit(workCellInstanceVo.getLimit() == null ? 10 : workCellInstanceVo.getLimit());
        workCellInstanceVo.setOffset(workCellInstanceVo.getOffset() == null ? 0 : workCellInstanceVo.getOffset());
        if (StringUtils.isNotEmpty(workCellInstanceVo.getSearch())) {
            workCellInstanceVo.setSearch(workCellInstanceVo.getSearch().trim());
        }
        jsonObject.put("total", workCellInstanceMapper.queryInstanceInfoUnionCount(workCellInstanceVo));
        jsonObject.put("rows", JSON.toJSON(workCellInstanceMapper.queryInstanceInfoUnionList(workCellInstanceVo)));
        return jsonObject;
    }

    /**
     * 根据ID查询一站一案和操作单元
     *
     * @param workInstanceId
     * @return
     * @throws Exception
     */
    @Override
    public WorkCellInstanceVo queryInstanceInfoUnionById(String workInstanceId) throws Exception {
        return workCellInstanceMapper.queryInstanceInfoUnionById(workInstanceId);
    }
    /**
     * @param entityTypeId 实体类型Id ， 生产单元id
     */
    @Override
    public List<Ztree> loadZtree(String entityTypeId,String iconSkin) throws Exception {
        List<Ztree> ztreeList = new ArrayList<>();
        /**
         * 实体ID 为空则查询全部的实体类型Ztree 和  生产实体类型
         * 实体ID 不为空 ， 则查询组织机构 或者 实体类型的孩子节点实体树
         */
        // 实体ID 为空则查询全部的实体类型Ztree 和  生产实体类型

            // 实体ID 不为空 ， 则查询组织机构 或者 实体类型的孩子节点实体树
            Organization organization = organizationService.findOrgById(entityTypeId);
            if(organization!=null && organization.getOrgLevelId().equals(OrganizationLevel.ORG_LEVEL_STATION.getCode())){
                Station station =  stationService.selectByPrimaryKey(entityTypeId); //
                // 属于组织 则查询组织
                if(station != null){
                    // 查询生产单元下所有的实体类型
                    if(station!=null && station.getServiceNodeId() !=null){
                        // 获取场站的业务体系中的生产单元
                        entityTypeId =  station.getServiceNodeId();
                    }
                }
            }else if(organization!=null && organization.getOrgLevelId().equals(OrganizationLevel.ORG_LEVEL_WELL.getCode())){
                   // 获取井站的业务体系中的生产单元
                    Well well = wellService.selectByPrimaryKey(entityTypeId);
                    if(well != null && well.getServiceNodeId() != null){
                        entityTypeId =  well.getServiceNodeId();
                    }
            }else {
                // 组织机构为空 存在 实体 和 其他组织机构
                if(iconSkin.equals(TreeIconSkin.ICON_ENTITY.getDesc())){
                        Entity entity = entityMapper.selectByEnId(entityTypeId);
                        if(entity != null && entity.getEnTypeId() != null){
                            entityTypeId = entity.getEnTypeId();
                        }
                }else {
                    entityTypeId = null ;
                }
            }
            // 判断当前是否绑定了业务体系 ， 如果没有绑定则查询全部的业务节点 和 业务节点下所有的实体类型
            if(entityTypeId == null ){
                // 获取当前节点中的
                List<Ztree>  list = entityTypeService.getAllEntityTypeZtree();
                ztreeList.addAll(list);
            }else{
                List<Ztree>  list = entityTypeService.getEntityTypeList(entityTypeId);
                ztreeList.addAll(list);
            }

        return ztreeList ;
    }

    /**
     * @param workCellInstanceId 一站一案复制新增
     */
    @Override
    public Map<String, Object> copyCard(String workCellInstanceId,EmployeeVo employeeVo) throws Exception {
        Map<String,Object> resMap = new HashMap<>();
        // 查询一站一案 ， 并复制成新增的内容
        String newInstanceId = UniqueUtil.uuid() ;
        WorkCellInstance newInstance = workCellInstanceMapper.selectByPrimaryKey(workCellInstanceId);
        WorkCellInstance oldInstance = workCellInstanceMapper.selectByPrimaryKey(workCellInstanceId);
            newInstance.setStepVersion(null);
            newInstance.setWorkInstanceId(newInstanceId);
            newInstance.setAliasName(newInstance.getAliasName()+"-副本");
            newInstance.setCreatetime(new Date());
            newInstance.setModifytime(new Date());
            newInstance.setCreateopid(employeeVo.getEmployeeId());
            newInstance.setModifyopid(employeeVo.getEmployeeId());
        Integer total = workCellInstanceMapper.insertSelective(newInstance);
            if(total > 0 ){
                resMap.put("state",true);
                resMap.put("msg","复制新增:一站一案基本信息成功！");
            }else{
                resMap.put("state",false);
                resMap.put("msg","复制新增:一站一案基本信息失败！");
            }

         // 复制当前步骤信息
        try {
            resMap =   operateUnitService.cloneStep(oldInstance,newInstance,employeeVo);
        } catch (Exception e) {
            resMap.put("state",false);
            resMap.put("msg","一站一案复制步骤失败");
            e.printStackTrace();
        }

        // 复制文档
        try {
            resMap = relatedDocService.cloneDoc(oldInstance,newInstance,employeeVo);
        } catch (Exception e) {
            resMap.put("state",false);
            resMap.put("msg","一站一案复制文档失败");
            e.printStackTrace();
        }

        // 复制关联数据
        try {
            dataSetService.cloneDataSet(oldInstance,newInstance ,employeeVo);
            resMap.put("state",true);
            resMap.put("msg","一站一案复制关联数据成功");
        } catch (Exception e) {
            resMap.put("state",false);
            resMap.put("msg","一站一案复制关联数据失败");
            e.printStackTrace();
        }

        resMap.put("state",true);
        resMap.put("msg","一站一案复制成功");

        return resMap ;
    }

    @Override
    public MajorStat majorStatistics(MajorStat majorStat){
        if(StringUtils.isEmpty(majorStat.getOrgId())){
            return null;
        }
        return workCellInfoMapper.majorStatistics(majorStat);
    }

    @Override
    public OpItemStat opItemStat(OpItemStat opItemStat){
        if(StringUtils.isEmpty(opItemStat.getOrgId())){
            return null;
        }
        return workCellInfoMapper.opItemStat(opItemStat);
    }
}
